import { mapGetters } from 'vuex'
import { excelJsonExport } from '@vimi/utils-tool'
import { exportTableColumns } from '@/bank/views/limit/index'
// 限率正常列表
export const limitNormalParams = {
  computed: {
    ...mapGetters(['user']),
    normalParams() {
      const { queryAddressCode, clientOrgClassType } = this.user
      return {
        address_code: queryAddressCode,
        'import_status.eq': 1,
        'bank_type.eq': clientOrgClassType,
      }
    },
  },
}

/**
 * 外部必须定义的数据：
 *
 * data
 *   - tableColumns
 *   - tableName
 *   - order
 *   - params
 *
 * methods
 *   - dataAdapter(row)
 *
 */
export default {
  mixins: [limitNormalParams],
  data() {
    return {
      loading: false,
      tableData: [],
      tableCount: 0,
      exportLoading: false,
      useManage: true,
    }
  },
  computed: {
    ...mapGetters(['userId', 'clientId', 'job', 'org', 'user']),
  },
  methods: {
    getParams() {
      return {
        ...this.normalParams,
        ...this.params,
      }
    },
    fetchData(params) {
      return this.$utils.promise(
        this.$api.getData(this.$serviceName, this.tableName, params, this.order || {})
      )
    },
    async getData(index = 1) {
      this.params.index = index
      this.loading = true
      const [res = {}] = await this.fetchData(this.getParams())
      this.loading = false

      const data = res.data || {}
      this.tableCount = data.totalCount || 0
      this.tableData = (data.data || []).map(this.dataAdapter)
    },
    async exportExcel(filename) {
      const exportTable = exportTableColumns.filter(item => !item.operations && !item.hidden)
      const header = {}
      const headerCellStyles = {}
      const columns = exportTable.map((item, i) => {
        const { prop, label } = item.attrs || {}
        header[prop] = label
        headerCellStyles[`${String.fromCharCode(65 + i)}1`] = { font: { bold: true } }
        return prop
      })

      this.exportLoading = true
      const { index, size, ...params } = this.getParams()
      const [res = {}] = await this.fetchData(params)

      const data = (res.data || []).map((item, index) => {
        return {
          index: index + 1,
          ...this.dataAdapter(item),
        }
      })

      excelJsonExport({
        columns,
        data: [header, ...data],
        filename,
        styles: {
          border: {
            left: { style: 'thin' },
            top: { style: 'thin' },
            right: { style: 'thin' },
            bottom: { style: 'thin' },
          },
          alignment: {
            vertical: 'center',
            horizontal: 'center',
            wrapText: true,
          },
        },
        cellStyles: {
          ...headerCellStyles,
        },
      }).finally(() => {
        this.exportLoading = false
      })
    },
  },
}
